
const http = require('http')

const tempalte = `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .component{
            display: none;
        }
    </style>

</head>
<body>
<ul>
    <li><a href="/home">home</a><li>
    <li><a href="/user">user</a><li>
    <li><a href="/about">about</a></li>
</ul>
<div id="routeView"></div>

<div class="component" data="home">
    home
</div>
<div class="component" data="user">
   user
</div>
<div class="component" data="about">
    about
</div>
</body>
<script>

    // 页面加载完不会触发 hashchange，这里主动触发一次 hashchange 事件
    window.addEventListener('DOMContentLoaded', onLoad)
    // 监听路由变化
   window.addEventListener('popstate', onPopState)
    // 路由视图
    var routerView = null
    function onLoad () {
        routerView = document.querySelector('#routeView')
        onPopState()
        // 拦截  标签点击事件默认行为， 点击时使用 pushState 修改 URL并更新手动 UI，从而实现点击链接更新 URL 和 UI 的效果。
        var linkList = document.querySelectorAll('a[href]')
        linkList.forEach(el => el.addEventListener('click', function(e) {

            e.preventDefault()

            window.history.pushState(null, null, el.getAttribute('href'))
            console.log( window.location.pathname+'000');

         onPopState()
        }))
    }
    // 路由变化时，根据路由渲染对应 UI
    function onPopState () {
        switch (location.pathname) {
            case '/home':
                routerView.innerHTML =  document.querySelector('[data=home]').innerHTML
                return
            case '/user':
                routerView.innerHTML =  document.querySelector('[data=user]').innerHTML
                return
            case '/about':
                routerView.innerHTML = document.querySelector('[data=about]').innerHTML
                return
            default:
                return
        }
    }

</script>
</html>
`

http.createServer(function(req,res){
res.write(tempalte)
    res.end()
}).listen(8081, (req, res) => {
    console.log('Server started...')

})


